﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using plust.Persistencia;

namespace plust.Content
{
    /// <summary>
    /// Interaction logic for LoginDialog.xaml
    /// </summary>
    public partial class LoginDialog : UserControl
    {
        PersistenciaDB persistencia = new PersistenciaDB();

        public bool autentificado = false;

        public LoginDialog()
        {
            InitializeComponent();
            this.Loaded += OnLoaded;
        }

        void OnLoaded(object sender, RoutedEventArgs e)
        {
            Keyboard.Focus(this.tbUsuario);
        }
        
        private void UserControl_Unloaded(object sender, RoutedEventArgs e)
        {
            if (!this.autentificado)
            {
                Application.Current.MainWindow.Close();
            }
        }

        private void btIngresar_Click(object sender, RoutedEventArgs e)
        {
            if(tbUsuario.Text == "" && pbPassword.Password == "" )
            {
                lbError.Text = "Ingrese usuario y password.";
                return;

            }else if(tbUsuario.Text == ""){

                lbError.Text = "Ingrese usuario";
                return;
            }
            else if (pbPassword.Password == "")
            {
                lbError.Text = "Ingrese password";
                return;
            }

            if (persistencia.obternerPasswordUsuario(this.tbUsuario.Text) != null)
            {
                string pass = persistencia.obternerPasswordUsuario(this.tbUsuario.Text);

                if (pass == pbPassword.Password)
                {
                    this.autentificado = true;

                    Window.GetWindow(this).Close();
                }
                else
                {
                    lbError.Text = "Hay un error en el password o usuario.";
                }
            }
            else
            {
                    lbError.Text = "Hay un error en el password o usuario.";
            }
        }
    }
}
